﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Wine.xaml.cs" company="Simon Carpentier">
//   Microsoft Reciprocal License (Ms-RL)
// </copyright>
// <summary>
//   Defines the Wine type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace VinoCellar
{
    using System;
    using System.Windows;

    using Microsoft.Phone.Controls;

    using VinoCellar.Model;

    public partial class Wine : PhoneApplicationPage
    {
        private WineItemFactory wineItemFactory = new WineItemFactory();
        private WineItem wineItem;

        public Wine()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string id;
            
            if (NavigationContext.QueryString.TryGetValue("id", out id))
            {
                wineItem = wineItemFactory.GetWineItem(int.Parse(id));
                wineDetailsControl.Load(wineItem);
                wineDetailsControl.Visibility = Visibility.Visible;
            }
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (e.Uri.OriginalString.Contains("New.xaml"))
            {
                e.Cancel = true;
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }

            base.OnNavigatingFrom(e);
        }

        private void appBarDeleteButton_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show(
                "Delete wine",
                "Are you sure you want to delete this wine?",
                MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                App.ViewModel.DeleteWineItem(this.wineItem);
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        private void appBarSaveButton_Click(object sender, EventArgs e)
        {
            App.ViewModel.SaveChangesToDB();
            MessageBox.Show("Changes saved successfully");
        }
    }
}